name: Build Corey on Ubuntu

on:
  push:
    branches: [ "main" ]
    paths-ignore:
      - 'coverage.json'
  pull_request:
    branches: [ "main" ]

env:
  BUILD_TYPE: Debug
  COV_COMMIT_AUTHOR: CoverageBot
  COV_COMMIT_MESSAGE: "readme: Update coverage report"
  
jobs:
  build:
    # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac.
    # You can convert this to a matrix build if you need cross-platform coverage.
    # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4
      with:
        token: ${{ secrets.COVBOT_SECRET }}

    - name: Install dependencies
      run: |
        sudo apt-get update && sudo apt-get install -y libboost-dev lcov 
        sudo pip3 install lcov_cobertura

    - name: Configure CMake
      run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCOREY_ENABLE_COVERAGE=TRUE

    - name: Build
      run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}

    - name: Test
      working-directory: ${{github.workspace}}/build
      run: ctest -C ${{env.BUILD_TYPE}}

    - name: Generate coverage report
      run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --target coverage
    
    - name: Update coverage summary
      run: |
        sed -nr 's/^.+lines\.+: ([0-9]+\.[0-9]+).+$/{"lines": \1,/p' ${{github.workspace}}/build/coverage.summary | tr -d '\n' > coverage.json
        echo -n '"date": "' >> coverage.json         
        date | tr -d '\n' >> coverage.json        
        echo '"}' >> coverage.json

    - name: Commit Coverage
      if: github.event_name == 'push'
      run: |
        git config --global user.name "${{ env.COV_COMMIT_AUTHOR }}"
        git config --global user.email "masscry@users.noreply.github.com"
        git add coverage.json
        git commit -m "${{ env.COV_COMMIT_MESSAGE }}"
        git push
